/*
 PureMVC AS3 Demo - Flex Employee Admin 
 Copyright (c) 2007-08 Clifford Hall <clifford.hall@puremvc.org>
 Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package vn.demand.dragon.model
{
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.MarketingApplicationFacade;
	import vn.demand.dragon.model.business.LoadMasterdataDelegate;

	public class MasterdataProxy extends Proxy implements IProxy, IResponder
	{
		public static const NAME:String = 'MasterdataProxy';
		
		public var errorStatus:String = null;
		
		private var companies:XMLListCollection = null;
		
		private var quotationStatuses:XMLListCollection = null;
		
//		private var customersStatuses:XMLListCollection = null;
		
		private var customerTypes:XMLListCollection = null;
	
		private var suppliers:XMLListCollection = null;
		
		private var items:XMLList;
		
		[Bindable]
		public var masterdataLoaded = false;
		
		public function MasterdataProxy( )
		{
			super( NAME, new XMLList());	
		}
		
		public function loadMasterdata():void {
			masterdataLoaded = false;
			var delegate:LoadMasterdataDelegate = new LoadMasterdataDelegate(this);
			delegate.loadMasterdataService();
		}

		// this is called when the delegate receives a result from the service
		public function result( rpcEvent : Object ) : void
		{
			masterdataLoaded = true;
			// populate the employee list in the proxy with the results from the service call
			RIALogger.debug(this, "Result load masterdata list");
			data = rpcEvent.result;
			items = data.items.item as XMLList;
			sendNotification( MarketingApplicationFacade.LOAD_MASTERDATA_SUCCESS );
		}
		
		// this is called when the delegate receives a fault from the service
		public function fault( rpcEvent : Object ) : void 
		{
			masterdataLoaded = false;
			data = new XMLList();
			// store an error message in the proxy
			// labels, alerts, etc can bind to this to notify the user of errors
			errorStatus = "Could not Load Masterdata!\n" + rpcEvent;
			Alert.show("" + rpcEvent);
			sendNotification( MarketingApplicationFacade.LOAD_MASTERDATA_FAILED);
			
		}

		public function get usersDP():XMLList {
			return data.users.type as XMLList;
		}
		
		public function getUserById(id:int):String {
			var results:XMLList = usersDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function get customersDP():XMLListCollection {
			if (null == companies) {
				companies = new XMLListCollection(data.customers.type);
				companies.addItemAt(new XML("<type><label></label><data>0</data><company_code></company_code></type>"), 0);
				var sort:Sort = new Sort();
				sort.fields = [new SortField('label', true)];
				companies.sort = sort;
			}
			return companies;
		}
		
		public function get quotationTypesDP():XMLList {
			return data.quotationTypes.type;
		}
		
		public function get quotationStatusesDP():XMLList {
			return data.quotationStatuses.type;
		}
		
		public function get companyTypesDP():XMLList {
			return data.companyTypes.type;
		}
		
		public function get companyStatusesDP():XMLList {
			return data.companyStatuses.type;
		}
		
		public function get currenciesDP():XMLList {
			return data.currencies.type;
		}
	
		public function get methodsDP():XMLList {
			return data.methods.type;
		}
		
		public function get unitsDP():XMLList {
			return data.units.type;
		}
		
		public function get containersDP():XMLList {
			return data.containers.type;
		}
	
		public function get shippingTypesDP():XMLList {
			return data.shippingTypes.type as XMLList;
		}
		
		public function get cargoTypesDP():XMLList {
			return data.cargoTypes.type as XMLList;
		}
		
		public function get vatTypesDP():XMLList {
			return data.vatTypes.type as XMLList;
		}
		
		public function get supplierStatusesDP():XMLList {
			return data.supplierStatuses.type as XMLList;
		}
		
		public function get divisionsDP():XMLList {
			return data.divisions.type as XMLList;
		}
		
		public function get costCentersDP():XMLList {
			return data.costcenters.type as XMLList;
		}
	
//		public function get itemsDP():XMLListCollection {
//			if (null == items) {
//				items = new XMLListCollection(data.items.item);
//				var sort:Sort = new Sort();
//				sort.fields = [new SortField('label', true)];
//				items.sort = sort;
//			}
//			return items;
//		}
		
//		public function get itemsDP():XMLList {
//			return data.items.item as XMLList;
//		}
		
		public function get taskItemsDP():XMLList {
			return items.(child('type') == 'Task') as XMLList;
		}
		
		public function get taskLogItemsDP():XMLList {
			return items.(child('type') == 'Task log') as XMLList;
		}
		
		public function get projectItemsDP():XMLList {
			return items.(child('type') == 'Customer product') as XMLList;
		}
		
		public function get expenseTypeDP():XMLList {
			return data.expenseTypes.type as XMLList;
		}
		
		public function get projectTypeDP():XMLList {
			return data.projectTypes.type as XMLList;
		}
		
		public function get projectStatusDP():XMLList {
			return data.projectStatuses.type as XMLList;
		}
		
		public function get supplierDP():XMLListCollection {
			if (null == suppliers) {
				suppliers = new XMLListCollection(data.suppliers.type);
				var sort:Sort = new Sort();
				sort.fields = [new SortField('label', true)];
				suppliers.sort = sort;
			}
			return suppliers;
		}
		
		public function get classificationDP():XMLList {
			return data.classifications.type as XMLList;
		}
		
		public function getClassificationById(id:int):String {		
			var results:XMLList = classificationDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
		
		public function get supplierTypesDP():XMLList {
			return data.supplierTypes.type as XMLList
		}
		
		public function getCompanyTypeById(id:int):String {		
			var results:XMLList = companyTypesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
		
		public function getSupplierTypeById(id:int):String {		
			var results:XMLList = supplierTypesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
		
		public function getProjectTypeById(id:int):String {		
			var results:XMLList = projectTypeDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
		
		public function getProjectStatusById(id:int):String {		
			var results:XMLList = projectStatusDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
	
		public function getExpenseTypeById(id:int):String {		
			var results:XMLList = expenseTypeDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
		
		public function isItemVAT(itemId:int):Boolean {
			 var list:XMLList = data.items.item.(child('data') == itemId);
			 if (list.length() <= 0) {
			 	return false;
			 }
			 return Number(list[0].vat_code_value) >= 0;
		}
		
		public function getContainerById(id:int):String {
			var results:XMLList = containersDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}

		public function getCargoTypeById(id:int):String {		
			var results:XMLList = cargoTypesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        		
        	} else {
        		return "";
        	}
		}
		
		public function getMethodById(id:int):String {
			var results:XMLList = methodsDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		public function getShippingTypeById(id:int):String {
			var results:XMLList = shippingTypesDP.(child('data') == id);
			if (results.length() > 0) {
        		return results[0].label;
        	}
        	return "";
		}
		
		public function getItemById(id:int, fullObject:Boolean=false):Object {
			var results:XMLList = items.(child('data') == id);
        	if (results.length() > 0) {
        		return fullObject ? results[0] : String(results[0].label);
        	}
        	return fullObject ? null : "";
		}
		
		public function getTaskLogItemById(id:int):String {
			var results:XMLList = taskLogItemsDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	}
        	return "";
		}
		
		public function getVATTypeById(id:int):String {
			switch (id) {
				case 0:	return '';
				case 1:	return 'Including';
				case 2:	return 'Excluding';
			}
			return "";
		}
		
		public function getCurrencyById(id:int):String {
			var results:XMLList = currenciesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		public function getUnitById(id:int):String {
			var results:XMLList = unitsDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function getQuotationTypeById(id:int):String {
			var results:XMLList = quotationTypesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function getQuotationStatusById(id:int):String {
			var results:XMLList = quotationStatusesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function getSupplierStatusById(id:int):String {
			var results:XMLList = supplierStatusesDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function getDivisionById(id:int):String {
			var results:XMLList = divisionsDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}

		public function getCostCenterById(id:int):String {
			var results:XMLList = costCentersDP.(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "" + id;
        	}
		}
		
		public function getCustomerById(id:int):String {
			var results:XMLList = data.customers.type.(Number(child('data')) == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function getSupplierById(id:int):String {
			var results:XMLList = supplierDP.children().(child('data') == id);
        	if (results.length() > 0) {
        		return results[0].label;
        	} else {
        		return "";
        	}
		}
		
		public function addObject(o:Object, type:String):void {
			try {
				var list:XMLListCollection = null;
				switch (type) {
					case 'company':
						list = customersDP;
						break;
					case 'supplier':
						list = supplierDP;
						break;
				}
				var found:int = -1;
				for(var i:int; i < list.length; i++) {
					var l:Object = list.getItemAt(i);
					if (Number(l.data) == Number(o.data)) {
						found = i;
					}
				}
				if (found < 0) {
					list.addItem(o);
				} else {
					list.setItemAt(o, found);
				}
				list.refresh();
			} catch (e:Error) {
				RIALogger.debug(this, e.getStackTrace());
				Alert.show(e.message);
			}
		}
		
		public function removeObject(o:Object, type:String):void {
			try {
				var list:XMLListCollection = null;
				switch (type) {
					case 'company':
						list = customersDP;
						break;
					case 'supplier':
						list = supplierDP;
						break;
				}
				var found:int = -1;
				for(var i:int; i < list.length; i++) {
					var l:Object = list.getItemAt(i);
					if (Number(l.data) == Number(o.data)) {
						found = i;
					}
				}
				if (found >= 0) {
					list.removeItemAt(found);
				}
				list.refresh();
			} catch (e:Error) {
				RIALogger.debug(this, e.getStackTrace());
				Alert.show(e.message);
			}
		}
		
		public function isProjectCompleted(projectVO):Boolean {
			return projectVO.project_rstatus == 2;
		}
		
		public function isProjectProcessed(projectVO):Boolean {
			return projectVO.project_rstatus == 13;
		}
		
		public function get currencyVND():int {
			return 5;
		}
		
		public function get currencyUSD():int {
			return 6;
		}
	}
}